# coding:utf-8
# -*- coding: utf-8 -*-
# @Time : 2020/12/17 20:36
# @Author: 王鹏-wangpeng99
# @File : uploadInfo.py

import re
import serial
import time
import traceback
from utils import logutils,consoleutils,uploadutils,dtutils

logger = logutils.getlogger(__file__)

ser = None

#####################################################
#################串口部分############################
####################################################
def init():
    global ser
    try:
        ser = serial.Serial("/dev/ttyAMA0", 9600, timeout=2)
        if not ser:
            raise serial.SerialException("打开串口错误")
        if not ser.isOpen():
            ser.open()
        logger.info("com:" + ser.name + " opened")
        ser.write("test\n".encode("utf-8"))
        time.sleep(0.1)
        resbytes = ser.readline()
        resstr = resbytes.decode().strip()
        logger.debug(resstr)
        if resstr != "test":
            raise serial.SerialException("test返回异常！")
    except serial.SerialTimeoutException as e1:
        traceback.print_exc()
        logger.error(traceback.format_exc())
        if ser and ser.isOpen():
            logger.debug("close ser")
            ser.close()
            ser = None
            return
    except serial.SerialException as e2:
        traceback.print_exc()
        logger.error(traceback.format_exc())
        if ser and ser.isOpen():
            logger.debug("close ser")
            ser.close()
            ser = None
            return
    except Exception as e3:
        traceback.print_exc()
        logger.error(traceback.format_exc())
        if ser and ser.isOpen():
            logger.debug("close ser")
            ser.close()
            ser = None
            return

# 关闭串口
def destroy():
    global ser
    if ser and ser.isOpen:
        ser.close()
        logger.info('com closed')

#发送串口命令
def sendTest():
    logger.debug("=================== sendTest ===================")
    cmdstr = "test\n"
    if cmdstr[-1] != '\n':
        cmdstr = cmdstr + "\n"
    logger.info("cmdstr={}".format(cmdstr).replace("\n", "\\n"))
    cmdbytes = cmdstr.encode("utf-8")
    ser.write(cmdbytes)
    time.sleep(0.1)
    reslst = []
    for _ in range(3):
        resbytes = ser.readline()
        resstr = resbytes.decode().strip()
        logger.info(resstr)
        reslst.append(resstr)
    return reslst

#发送串口命令
def sendCmd(cmdstr="test\n"):
    logger.debug("=================== sendCmd ===================")
    if cmdstr[-1] != '\n':
        cmdstr = cmdstr + "\n"
    logger.info("cmdstr={}".format(cmdstr).replace("\n", "\\n"))
    cmdbytes = cmdstr.encode("utf-8")
    ser.write(cmdbytes)
    time.sleep(0.1)
    reslst = []
    for _ in range(3):
        resbytes = ser.readline()
        resstr = resbytes.decode().strip()
        if len(resstr) == 0:
            break
        logger.info(resstr)
        reslst.append(resstr)
    return reslst

#############################################
#############读取当前wifi信号强度############
############################################

def getWifiInfo():
    try:
        rawinfo = consoleutils.execute_command("cat /proc/net/wireless|grep wlan0")
    except Exception:
        logger.error(traceback.format_exc())
        exit(1)
    logger.debug("rawinfo={}".format(rawinfo))
    datalst=rawinfo.split()
    #信号强度
    link = datalst[2][:-1]
    #信号质量
    level = datalst[3][:-1]
    #背景噪声
    noise = datalst[4]
    logger.info("link:{} level:{} noise:{}".format(link,level,noise))
    return link,level,noise

#############################################
##################获取数据并上传##############
############################################

def uploadVoltCurrent():
    dtstr = dtutils.currentTimeStamp()
    reslst = sendCmd("readVoltCurrent")
    resstr = " ".join(reslst)
    # 找到返回数据
    lst = re.findall(r"(?<=volt:)(\d+\.*\d*)", resstr)
    volt = lst[0]
    lst = re.findall(r"(?<=current:)(\d+\.*\d*)", resstr)
    current = lst[0]
    logger.info("volt:{} current:{}".format(volt, current))
    uploadutils.uploadVoltCurrent(dtstr, volt, current)


if __name__ == '__main__':
    init()
    if ser:
        uploadVoltCurrent()
    destroy()
    lst=getWifiInfo()
    if lst and len(lst)==3:
        uploadutils.uploadWifi(link=lst[0],level=lst[1],noise=lst[2])
    logger.info("完成")
